package com.rabc.web.aspect;

import com.rabc.web.annotation.Loggable;
import com.rabc.web.entity.SysOptionLog;
import com.rabc.framework.AsyncManager;
import com.rabc.framework.factory.AsyncFactory;
import com.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
public class LoggingAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @AfterReturning(pointcut = "@annotation(Loggable)", returning = "jsonResult")
    public void loggableMethods(JoinPoint joinPoint ,Loggable Loggable, Object jsonResult) {

        SysOptionLog optionLog=new SysOptionLog();
        System.out.println(joinPoint.getSignature().getDeclaringTypeName());
        // 获取类名和方法名
        String className = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();

        // 获取 HttpServletRequest
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 获取请求信息
        String requestUrl = request.getRequestURL().toString();
        String requestMethod = request.getMethod();

        // 打印或记录请求信息
        System.out.println("Class Name: " + className);
        System.out.println("Method Name: " + methodName);
        System.out.println("Request URL: " + requestUrl);
        System.out.println("Request Method: " + requestMethod);
        System.out.println("Client IP: " + IpUtils.getClientIp(request));
        System.out.println("Response: " + jsonResult);
         optionLog.setMethodName(methodName);
         optionLog.setRequestIp(IpUtils.getClientIp(request));
         optionLog.setRequestUrl(requestUrl);
      AsyncManager.getInstance().execute(AsyncFactory.recordOper(optionLog));
    }

//    @Before("loggableMethods()")
//    public void logMethodEntry(JoinPoint joinPoint) {
//        String methodName = joinPoint.getSignature().getName();
//        logger.info("Entering method: " + methodName);
//    }
//
//    @After("loggableMethods()")
//    public void logMethodExit(JoinPoint joinPoint) {
//        String methodName = joinPoint.getSignature().getName();
//        logger.info("Exiting method: " + methodName);
//    }
}
